package com.imooc.LinkedList.removeLinkedListElements;

/**
 * 删除值
 */
public class Solution {

    public ListNode removeElements(ListNode head, int val) {
        // 处理head == val的特殊情况
        while(head != null && head.val == val) {
            ListNode delNode = head;
            head = head.next;
            delNode.next = null;
        }

        // 防止所有元素都被删除的情况
        if(head == null) {
            return null;
        }

        ListNode pre = head;
        while (pre.next != null) {
            if(pre.next.val == val){
                ListNode delNode = pre.next;
                pre.next = delNode.next;
                delNode.next = null;
            }else
                pre = pre.next;
        }
        return head;
    }

    public static void main(String[] args) {
        int[] arr = {1,2,3,3,3,5,6,3};
        ListNode head = new ListNode(arr);
        System.out.println(head);
        Solution solution = new Solution();
        solution.removeElements(head, 3);
        System.out.println(head);
    }
}
